import serial
import serial.tools.list_ports as list_ports
from datetime import datetime
import csv

PID_MICROBIT = 516
VID_MICROBIT = 3368
TIMEOUT = 0.1


def find_comport(pid, vid, baud):
    ''' return a serial port '''
    ser_port = serial.Serial(timeout=TIMEOUT)
    ser_port.baudrate = baud
    ports = list(list_ports.comports())
    print('scanning ports')
    for p in ports:
        print('port: {}'.format(p))
        try:
            print('pid: {} vid: {}'.format(p.pid, p.vid))
        except AttributeError:
            continue
        if (p.pid == pid) and (p.vid == vid):
            print('found target device pid: {} vid: {} port: {}'.format(
                p.pid, p.vid, p.device))
            ser_port.port = str(p.device)
            return ser_port
    return None

def linelogger(line):
    dt = datetime.now()
    linewithtime = line.split(",")
    linewithtime.append( dt.strftime( '%Y-%m-%d %H:%M:%S' ) )
    with open("dht11data.csv", "a+", newline='') as df:
        csv_file = csv.writer(df)
        csv_file.writerow(linewithtime)


def main():
    print('looking for microbit')
    ser_micro = find_comport(PID_MICROBIT, VID_MICROBIT, 115200)
    #ser_micro = 'COM3'
    if not ser_micro:
        print('microbit not found')
        return
    print('opening and monitoring microbit port')
    ser_micro.open()
    while True:
        line = ser_micro.readline().decode('utf-8').strip()
        if line and line[0] != 'E':  # If it isn't a blank line and no Error.
            linelogger(line)
            print(line)
    ser_micro.close()

if __name__=="__main__":
    main()